package com.shwread.android.qysw.activity;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.ScrollView;
import android.widget.TextView;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.hzdracom.epubreader.activity.ReadingEpubActivity;
import com.hzdracom.epubreader.consts.EpubConst;
import com.hzdracom.epubreader.util.CSSHelp;
import com.shwread.android.qysw.activity.MyCommentActivity.CommentItemViewHolder;
import com.shwread.android.qysw10000182.R;
import com.shwread.android.ui.customview.MyListView;
import com.shwread.android.ui.dialog.DownloadDialog;
import com.shwread.android.ui.dialog.DownloadDialog.DownLoadDialogClickListener;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.widget.BookCoverView;
import com.shwread.android.ui.widget.CircleImageView;
import com.shwread.android.ui.widget.CommentView;
import com.shwread.android.ui.widget.ListenSoftInputMethodLinearLayout;
import com.shwread.android.ui.widget.ListenSoftInputMethodLinearLayout.OnSoftInputMethodListener;
import com.shwread.android.ui.widget.LoadingView;
import com.shwread.http.base.EmptyHttpResponseHandler;
import com.shwread.http.base.Log;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.util.JSONUtil;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.http.callback.IoTaskProgress;
import com.shwread.httpsdk.http.download.DownloadForProgressAction;
import com.shwread.httpsdk.http.face.QryCommentListAction;
import com.shwread.httpsdk.http.face.QryCommentPraiseNumAction;
import com.tgx.tina.android.task.ATaskService;

import org.apache.http.Header;
import org.geometerplus.android.util.QyreaderPerferencesUtil;
import org.json.JSONException;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import base.tina.core.task.infc.ITaskProgress.TaskProgressType;
import logic.bean.BookBean;
import logic.bean.BookInfo;
import logic.bean.ChapterInfo;
import logic.bean.CommentBean;
import logic.bean.DownLoadInfo;
import logic.bean.NewBookBean;
import logic.bean.NumberInfo;
import logic.bean.TOCItem;
import logic.beanenum.BookStatus_Enum;
import logic.beanenum.BookType_Enum;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.dao.BookDao;
import logic.util.DateUtil;
import logic.util.FileUtil;
import logic.util.ImageLoaderUtil;
import logic.util.NetworkUtil;
import logic.util.SDcardUtil;
import logic.util.Util;
import logic.util.Utils;
import logic.util.logutil.LogUtil;
import logic.util.qryChapterInfoUtil;
import logic.xml.parser.NCXHandler;


/**
 * 新的书籍详情页面
 */
public class NewBookDetailActivity extends BaseBusinessActivity implements OnClickListener {
    /**
     * 记录当前书籍下载任务列表
     */
    private static HashMap<Integer, BookInfo> downloadMap = new HashMap<>();
    private static final int MAX_DOWNLOAD_SIZE = 3;
    private static int notificationId = 0;
    private int currNotificationId;
    private static final int GET_CHAPTERLIST_OK = 100;
    private static final int GET_CHAPTERLIST_ERROE = GET_CHAPTERLIST_OK + 1;
    private static final int GET_CHAPTERINFO_OK = GET_CHAPTERLIST_ERROE + 1;
    private static final int GET_CHAPTERINFO_ERROR = GET_CHAPTERINFO_OK + 1;
    private static final int GET_BOOKINFO_OK = GET_CHAPTERINFO_ERROR + 1;
    private static final int GET_BOOKINFO_ERROR = GET_BOOKINFO_OK + 1;
    private static final int BOOKCOMMENTS_MAX_SIZE = 5;

    private TextView tvTitle, tvName, tvAuthor, tvClassify, tvStatus, tvRecommend, tvLongIntro;
    private View recommendView, body;
    private ImageView imgType;
    private BookCoverView imgCover;
    //	private SmartImageView                    imgCover;
    private Button btnBack;
    private TextView tvRead;
    private TextView tvDownload;
    private TextView tvTotalChapter;
    private LinearLayout llColumn;

    private BookInfo bean;
    private DownLoadInfo downInfo;
    private Context context;

    //	private WebImage                          webImage;
    private DownloadDialog dialog;
    private NotificationManager manager;
    private Notification notif;
    private PendingIntent pIntent;

    private List<TOCItem> catalogList;
    private BookDao bookMarkDao;
    //	private AddShelfBookAction  addShelfBookAction;

    private View loadingView;
    private ImageView loadingImg;
    private AnimationDrawable animationDrawable;
    private boolean isDownloadingCatalog = false;
    //与评论相关
    private View ll_book_detail, rl_book_comments;
    private View ll_switch_detail, ll_switch_comment;
    private TextView tv_book_detail, tv_book_comment, tv_getmore;
    private View line_book_detail, line_book_comment;
    private MyListView lv_comments;
    private CommentView comment_view;
    private LoadingView commentsLoadingView;
    private int contentType;                                                              //1 为书籍详情， 2 为书籍评论
    private List<CommentBean> bookComments;
    private BookCommentsAdapter commenetsAdapter;
    private int refreshType;                                                              //1 为初始装载， 2为刷新
    private int commentsCount;
    private InputMethodManager inputMethodManager;
    private boolean getBookInfoOk = true;

    private ListenSoftInputMethodLinearLayout root_view;
    private boolean inputMethodIsShow = false;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GET_CHAPTERLIST_OK:
                    dialog.setMessage(bean.getName(), downInfo.getFileSize(), bean.getLogoUrl(), bean.getBookId());
                    dialog.show();
                    break;
                case GET_CHAPTERLIST_ERROE:
                    Util.showToast(context, "该书已下架");
                    break;
                case DefaultConsts.UPDATEUI_BOOKSHELF_BOOKS_OK:
                    onlineRead(bean.getContent_type());
                    //toReadingBookActivity(chapter_index);
                    break;
                case GET_BOOKINFO_OK:
                    getBookInfoOk = true;
                    setView();
                    downloadDirecoty(bean.getNcxUrl());
                    break;
                case GET_BOOKINFO_ERROR:
                    getBookInfoOk = false;
                    Util.showToast(context, "获取书籍信息失败");
                    break;
                case DefaultConsts.COMMENT_SUBMIT_SUCCESS:
                    //Util.showToast(context, "添加评论成功");
                    getBookCommenets(2);//刷新评论
                    break;
                case DefaultConsts.COMMENT_SUBMIT_ERROR:
                    //Util.showToast(context, "添加评论失败");
                    break;
                default:
                    break;
            }
        }
    };
    /**
     * 是否已下载
     */
    private boolean isDown = false;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        bookMarkDao = BookDao.getInstance(this);
        if (getIntent().hasExtra("BookInfo")) {
            bean = (BookInfo) getIntent().getSerializableExtra("BookInfo");
            suffix = null != bean && !TextUtils.isEmpty(bean.getDownType()) && bean.getDownType().equals("103") ? EpubConst.EPUB_SUFFIX : ".ceb";
        }
        if (bean == null) {
            Util.showToast(this, "书籍已下架");
            finish();
            return;
        } else if (Util.isEmpty(bean.getAuthor())) {
            showLoading();
            //			new QryBookInfoByIdAction(context, bean.getBookId(), new BookInfoListener()).start();
            NewActionHelp.qryBookInfoById(context, bean.getBookId(), new BookInfoHandler());
        }
        if (getIntent().hasExtra(DefaultConsts.message_send_id)) {
            int msgViewId = getIntent().getIntExtra(DefaultConsts.message_send_id, -1);
            //			new ReadMsgBySendIdAction(this, String.valueOf(msgViewId), new EmptyAction()).start();
            NewActionHelp.readMsgBySendId(this, String.valueOf(msgViewId), new EmptyHttpResponseHandler());
        }
        mAService = new ATaskService();
        mAService.startAService(context);
        //addShelfBookAction = new AddShelfBookAction(this);
        findViews();
        updateLoadingView(1);
        setView();
        setListener();

        final String ncxPath = FileUtil.OnlinePath(String.valueOf(bean.getBookId())) + FileUtil.Book_CATALOGUE;
        if (!FileUtil.exists(ncxPath)) {
            downloadDirecoty(bean.getNcxUrl());
        } else {
            initDirctory(BookStatus_Enum.ONLINE.getValue());
            tvTotalChapter.setText(getResources().getString(R.string.chapter_total, bean.getTotalChapters()));
        }
        switchContent(1);
        //获取评论数
        new QryCommentPraiseNumAction(this, "1", String.valueOf(bean.getBookId()), new BookCommentsNumberActionListener(true)).start();

        if (null != bean && !TextUtils.isEmpty(bean.getDownType()) && bean.getDownType().equals("103")) {
            initCSS(bean.getBookId());
        }
    }

    //	@Override
    //	public boolean onKeyDown(int keyCode, KeyEvent event)  {
    //	    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { //按下的如果是BACK，同时没有重复
    //	    	restoreCommentView( );
    //	    }
    //	    return super.onKeyDown(keyCode, event);
    //	}

    private boolean resetCommentView() {
        if (inputMethodIsShow) {
            comment_view.setDefaultHint();
            comment_view.setCommentParams(NewBookDetailActivity.this, "1", bean.getBookId() + "");
            comment_view.hideInputMethod();
            return true;
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (!existMainActivity()) {
            startActivity(new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP));
        }
    }

    @Override
    protected void onPause() {
        //closeLoading();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (mAService != null) {
            mAService.stopAService();
        }
        super.onDestroy();
    }

    @Override
    public Handler getUIHandler() {
        return handler;
    }

    private void findViews() {
        setContentView(R.layout.book_new_detail);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        tvTitle = (TextView) findViewById(R.id.book_detail_header_name);
        btnBack = (Button) findViewById(R.id.book_detail_header_back);
        btnBack.setOnClickListener(this);

        body = findViewById(R.id.book_detail_body);
        tvName = (TextView) findViewById(R.id.book_detail_name);
        tvAuthor = (TextView) findViewById(R.id.book_detail_author);
        tvClassify = (TextView) findViewById(R.id.book_detail_classify);
        tvStatus = (TextView) findViewById(R.id.book_detail_status);
        recommendView = findViewById(R.id.book_detail_recommend_layout);
        tvRecommend = (TextView) findViewById(R.id.book_detail_recommend);
        tvLongIntro = (TextView) findViewById(R.id.book_detail_long_intro);
        imgCover = (BookCoverView) findViewById(R.id.book_detail_cover);
        //		imgCover = (SmartImageView) findViewById(R.id.book_detail_cover);
        imgType = (ImageView) findViewById(R.id.book_detail_type);
        tvRead = (TextView) findViewById(R.id.book_detail_will_read);
        tvRead.setOnClickListener(this);
        tvDownload = (TextView) findViewById(R.id.book_detail_download);
        tvDownload.setOnClickListener(this);
        llColumn = (LinearLayout) findViewById(R.id.book_detail_column);
        llColumn.setOnClickListener(this);
        tvTotalChapter = (TextView) findViewById(R.id.directory_total_num_tv);

        //评论相关
        ll_book_detail = findViewById(R.id.ll_book_detail);
        rl_book_comments = findViewById(R.id.rl_book_comments);
        ll_switch_detail = findViewById(R.id.ll_switch_detail);
        ll_switch_comment = findViewById(R.id.ll_switch_comment);
        line_book_detail = findViewById(R.id.line_book_detail);
        line_book_comment = findViewById(R.id.line_book_comment);
        tv_book_detail = (TextView) findViewById(R.id.tv_book_detail);
        tv_book_comment = (TextView) findViewById(R.id.tv_book_comment);
        lv_comments = (MyListView) findViewById(R.id.lv_comments);
        commenetsAdapter = new BookCommentsAdapter();
        lv_comments.setAdapter(commenetsAdapter);
        lv_comments.setOnItemClickListener(bookCommentsItemClickListener);
        tv_getmore = (TextView) findViewById(R.id.tv_getmore);
        comment_view = (CommentView) findViewById(R.id.comment_view);
        commentsLoadingView = (LoadingView) findViewById(R.id.comment_loadingview);

        loadingView = findViewById(R.id.common_loading_layout);
        loadingImg = (ImageView) findViewById(R.id.common_loading__img);
        if (bean.getContent_type() != null && bean.getBookType() != null) {
            if (bean.getContent_type().equals("2") && bean.getBookType().equals("2"))
                tvDownload.setVisibility(View.GONE);
        }
        dialog = new DownloadDialog(context);
        initCommentsLoadingView();
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        ScrollView sv_detail_body = (ScrollView) findViewById(R.id.sv_detail_body);
        sv_detail_body.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    boolean result = resetCommentView();
                    return result;
                }
                return false;
            }
        });

        root_view = (ListenSoftInputMethodLinearLayout) findViewById(R.id.root_view);
        root_view.setOnSoftInputMethodListener(new OnSoftInputMethodListener() {
            @Override
            public void OnSoftInputMethodChanged(boolean isShow) {
                inputMethodIsShow = isShow;
            }
        });

    }

    private void initCommentsLoadingView() {
        commentsLoadingView.setLoadingAnim(R.drawable.home_progress);
        commentsLoadingView.setEmptyView(R.drawable.icon_comment_empty, R.string.comment_empty_text);
        commentsLoadingView.setFailView(R.drawable.icon_loading_failed, R.string.comment_loading_failed);
        commentsLoadingView.setFailClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                updateCommentsHintUI(0);//加载动画
                getBookCommenets(1);
            }
        });
    }

    /**
     * @param flag -1：加载失败 ， 0:加载中，1：加载为空，2为加载成功
     */
    private void updateCommentsHintUI(int flag) {
        if (flag == 2) {
            lv_comments.setVisibility(View.VISIBLE);
            commentsLoadingView.setVisibility(View.GONE);
        } else {
            lv_comments.setVisibility(View.GONE);
            commentsLoadingView.setVisibility(View.VISIBLE);
        }
        commentsLoadingView.changeLoadingStatus(flag);
        lv_comments.getParent().getParent().requestLayout();
    }

    private void setView() {
        setBookTypeIcon(imgType, bean.getContent_type());

        //		tvTitle.setText(bean.getName());
        tvTitle.setText("书籍详情");
        tvName.setText(bean.getName());
        imgCover.setImageUrl(bean.getLogoUrl(), bean.getCoverTagPicUrl());
        //		imgCover.setImageUrl(bean.getLogoUrl());
        tvAuthor.setText("作者：" + bean.getAuthor());
            String type= bean.getFirstSortName() == null ? "" : bean.getFirstSortName();
            tvClassify.setText("分类：" + type);
        final String isFinished = bean.getIsFinished();
        if (!TextUtils.isEmpty(isFinished)) {
            tvStatus.setText(isFinished.toLowerCase().equals("y") ? "状态：已完结" : "状态：未完结");
        }
        if (TextUtils.isEmpty(bean.getEditorRecommend())) {
            recommendView.setVisibility(View.GONE);
        } else {
            recommendView.setVisibility(View.VISIBLE);
            tvRecommend.setText(bean.getEditorRecommend());
        }
        tvLongIntro.setText(bean.getLongIntro());

        final String tempPath = FileUtil.DownloadPath() + bean.getBookId() + suffix;
//		final String tempPath = FileUtil.DownloadPath() + bean.getBookId() + ".ceb";
        if (FileUtil.exists(tempPath)) {
            tvDownload.setText("已下载");
            //			tvDownload.setEnabled(false);
            isDown = true;
        }

        if (bean.getContent_type() != null && bean.getBookType() != null) {
            if (bean.getContent_type().equals("2") && bean.getBookType().equals("2"))
                tvDownload.setVisibility(View.GONE);
        }
    }

    void setListener() {
        dialog.setPageListener(new DownLoadDialogClickListener() {

            @Override
            public void okListener(View v) {
                dialog.dismiss();
                downloadBook();
            }

            @Override
            public void cancelListener(View v) {
                dialog.dismiss();
            }
        });

        ll_switch_detail.setOnClickListener(this);
        ll_switch_comment.setOnClickListener(this);
        tv_getmore.setOnClickListener(this);
    }

    void addBooktoShelf(int status, int chapterIndex) {
        bookMarkDao.addBooktoShelf(toBookBean(status, chapterIndex, bean));
        //		onlineRead(bean.getContent_type());
    }

    private BookBean toBookBean(int status, int chapterIndex, BookInfo bean) {
        String path = "";
        if (status == BookStatus_Enum.DOWNLOAD.getValue()) {
            path = FileUtil.DownloadPath() + String.valueOf(bean.getBookId()) + ".ceb";
        } else if (status == BookStatus_Enum.ONLINE.getValue()) {
            path = FileUtil.OnlinePath(String.valueOf(bean.getBookId())) + "toc.ncx";
        }
        if ("1".equals(bean.getBookType())) {
            bean.setContent_type("6");
        }
        BookBean bookbean = new BookBean(status, bean.getBookId(), bean.getName(), Integer.parseInt(bean.getContent_type()), chapterIndex, path, bean.getAuthor(), Const.phone_number, String.valueOf(System.currentTimeMillis()), bean.getLogoUrl());
        return bookbean;
    }

    /**
     * 跳转阅读页面
     *
     * @param index 设定文件
     */
    void readTextBook(int index) {
        if ((chapter_index < catalogList.size() - 1) && !FileUtil.FileExist(String.valueOf(bean.getBookId()),
                catalogList.get(chapter_index + 1).getId() + ".html")) {
            //			new QryChapterInfoAction(context, String.valueOf(bean.getBookId()), catalogList.get(index + 1).getId(), null).start();
            new qryChapterInfoUtil().qryChapterInfo(context, String.valueOf(bean.getBookId()), catalogList.get(index + 1).getId());
        }
        Intent intent = new Intent(context, ReadingBookActivity.class);
        intent.putExtra(DefaultConsts.book_contentId_s, String.valueOf(bean.getBookId()));
        intent.putExtra(DefaultConsts.chapterId_index_i, index);
        intent.putExtra(DefaultConsts.book_name, bean.getName());
        intent.putExtra("IsFromCatalogActivity", true);
        String path = FileUtil.OnlinePath(String.valueOf(bean.getBookId())) + "toc.ncx";
        Uri url = Uri.parse(path);
        intent.setData(url);
        intent.putExtra(ReadingBookActivity.BOOKSTATUS, BookStatus_Enum.ONLINE.getValue());
        startActivity(intent);
    }

    void readMagazineBook() {
        BookBean bookbean = toBookBean(BookStatus_Enum.ONLINE.getValue(), chapter_index, bean);
        Intent intent = new Intent(this, ReadingmagazineActivity.class);
        //		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("BookMarkBean", bookbean);
        intent.putExtra(DefaultConsts.chapterId_index_i, chapter_index);
        startActivity(intent);
        if ((chapter_index < catalogList.size() - 1) && !FileUtil.FileExist(String.valueOf(bean.getBookId()), catalogList.get(chapter_index + 1).getId() + ".html")) {
            //			new QryChapterInfoAction(context, String.valueOf(bean.getBookId()), catalogList.get(chapter_index + 1).getId(), null).start();
            new qryChapterInfoUtil().qryChapterInfo(context, String.valueOf(bean.getBookId()), catalogList.get(chapter_index + 1).getId());
        }
    }

    /**
     * 跳转目录页面
     */
    public void goCatalogActivity() {
        Intent intent = new Intent(this, CatalogActivity.class);
        intent.putExtra("BookInfo", bean);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK != resultCode) return;
        if (requestCode == COMMENTS_REQUEST_CODE) {
            //刷新评论数
            getBookCommenets(2);//刷新评论
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.book_detail_header_back://返回
                comment_view.hideInputMethod();
                onBackPressed();
                break;
            case R.id.book_detail_will_read://立即阅读
                if (!SDcardUtil.isSDCARDMounted()) {
                    Util.showToast(this, getResources().getString(R.string.image_save_sdcard_deny));
                    return;
                }
                if (Util.isEmpty(bean.getContent_type())) {
                    Util.showToast(context, "服务器数据返回错误");
                    return;
                }
                if (isDownloadingCatalog) {
                    Util.showToast(context, "正在下载目录，请稍等");
                    return;
                }
                //epub3电子书
                if (null != bean && bean.getDownType().equals("103")) {
                    readEpub3();
                    return;
                }
                if (isDown) {
                    System.out.println("离线阅读");
                    readDownloadBook();
                } else {
                    System.out.println("在线阅读");
                    if (NetworkUtil.isNetAvailable(context)) {
                        readBook();
                    } else {
                        new NoNetDialog(context).show();
                    }
                }
                break;
            case R.id.book_detail_download://下载书籍
                if (!SDcardUtil.isSDCARDMounted()) {
                    Util.showToast(this, getResources().getString(R.string.image_save_sdcard_deny));
                    return;
                }
                if (Util.isEmpty(bean.getContent_type())) {
                    Util.showToast(context, "服务器数据返回错误");
                    return;
                }
                if (!NetworkUtil.isNetAvailable(context) && !isDown) {
                    new NoNetDialog(context).show();
                } else {
                    final String str = tvDownload.getText().toString();
                    switch (str) {
                        case "已下载":
                            Util.showToast(context, "下载完成，可在" + getResources().getString(R.string.maintab_bookshelf) + "查看");
                            break;
                        case "下载":
                            getDownloadInfo();
                            break;
                        default:
                            Util.showToast(context, "正在下载");
                            break;
                    }
                }
                break;
            case R.id.book_detail_column://书籍目录
                if (NetworkUtil.isNetAvailable(context)) {
                    goCatalogActivity();
                } else {
                    new NoNetDialog(context).show();
                }
                break;
            case R.id.ll_switch_detail: //详情
                switchContent(1);
                break;
            case R.id.ll_switch_comment: //评论
                switchContent(2);
                break;
            case R.id.tv_getmore: //查看更多评论
                viewMoreComments();
                break;
            default:
                break;
        }
    }

    /**
     * 查看更多评论
     */
    private void viewMoreComments() {
        Intent intent = new Intent(this, CommentListActivity.class);
        intent.putExtra(DefaultConsts.COMMENT_TARGET_TYPE, "1");
        intent.putExtra(DefaultConsts.COMMENT_TARGET_VALUE, bean.getBookId() + "");
        startActivityForResult(intent, COMMENTS_REQUEST_CODE);
    }

    /**
     * 切换要显示的内容
     *
     * @param type 1为书籍详情， 2为书籍评论
     */
    private void switchContent(int type) {
        if (bean == null || !getBookInfoOk) {
            Util.showToast(this, "此书已下架");
            return;
        }
        if (contentType == type) {
            return;
        }
        contentType = type;
        if (contentType == 1) {//书籍详情
            ll_book_detail.setVisibility(View.VISIBLE);
            rl_book_comments.setVisibility(View.GONE);

            tv_book_detail.setTextColor(0xfff79535);//选中色
            tv_book_comment.setTextColor(0xff323232);//非选中色

            line_book_detail.setVisibility(View.VISIBLE);
            line_book_comment.setVisibility(View.INVISIBLE);
            comment_view.setVisibility(View.GONE);
        } else if (contentType == 2) {//书籍评论
            ll_book_detail.setVisibility(View.GONE);
            rl_book_comments.setVisibility(View.VISIBLE);

            tv_book_detail.setTextColor(0xff323232);//非选中色
            tv_book_comment.setTextColor(0xfff79535);//选中色

            line_book_detail.setVisibility(View.INVISIBLE);
            line_book_comment.setVisibility(View.VISIBLE);
            comment_view.setVisibility(View.VISIBLE);
            rl_book_comments.getParent().requestLayout();
            //获取评论的内容
            if (bookComments == null || bookComments.size() == 0) {
                comment_view.setDefaultHint();
                comment_view.setCommentParams(this, "1", bean.getBookId() + "");
                updateCommentsHintUI(0);//加载动画
                getBookCommenets(1);
            }
        }
    }

    //评论项的click 事件
    OnItemClickListener bookCommentsItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
            CommentBean itemBean = bookComments.get(position);
            String commentUser = itemBean.getCommentUserAccount();
            String targetType = "1";
            String targetValue = bean.getBookId() + "";
            long commentId = itemBean.getCommentId();

            if (Const.phone_number.equalsIgnoreCase(commentUser)) {
                //点击到了自己的评论
                comment_view.setDefaultHint();
                comment_view.setCommentParams(NewBookDetailActivity.this, targetType, targetValue);
            } else {
                //点击到了别人的评论
                long targetUserId = itemBean.getCommentUserId();
                comment_view.setHintString(itemBean.getCommentUserNickName());
                comment_view.setReplyParams(NewBookDetailActivity.this, targetType, targetValue, targetUserId, commentUser, commentId);
            }
            //显示输入法
            comment_view.showInputMethod();
        }
    };

    /**
     * 获取书籍的评论
     *
     * @param flag 1为初始加载， 2为刷新
     */
    private void getBookCommenets(int flag) {
        if (bean == null) return;
        refreshType = flag;
        if (NetworkUtil.isNetAvailable(this)) {
            //获取评论
            new QryCommentListAction(this, "1", String.valueOf(bean.getBookId()), 0L, BOOKCOMMENTS_MAX_SIZE, new BookCommentsActionListener()).start();
            //获取评论数
            new QryCommentPraiseNumAction(this, "1", String.valueOf(bean.getBookId()), new BookCommentsNumberActionListener(false)).start();
        } else {
            updateCommentsHintUI(-1);
            if (refreshType == 1) {
                new NoNetDialog(this).show();
            } else {
                Util.showToast(context, "刷新失败");
            }
        }
    }

    void readDownloadBook() {
        chapter_index = QyreaderPerferencesUtil.getInstance(context, Const.phone_number).getChapterIndex(String.valueOf(bean.getBookId()));
        bookMarkDao.addBooktoShelf(toBookBean(BookStatus_Enum.DOWNLOAD.getValue(), chapter_index, bean));

        int index = QyreaderPerferencesUtil.getInstance(this, Const.phone_number).getLocalIndex(String.valueOf(bean.getBookId()));
        Intent intent = new Intent(this, ReadingBookActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(ReadingBookActivity.BOOKSTATUS, BookStatus_Enum.DOWNLOAD.getValue());
        intent.putExtra(DefaultConsts.book_contentId_s, String.valueOf(bean.getBookId()));
        intent.putExtra(DefaultConsts.chapterId_index_i, index);
        intent.putExtra(DefaultConsts.book_name, bean.getName());
        String urlpath = FileUtil.DownloadPath() + String.valueOf(bean.getBookId()) + ".ceb"; //"/oebps"
        Uri url = Uri.parse(urlpath);
        intent.setData(url);
        startActivity(intent);
    }

    void onlineRead(String type) {
        if (null == bean || null == catalogList) {
            //closeLoading();
            Util.showToast(context, "该书已下架");
            return;
        }
        if (type.equals(BookType_Enum.BOOK.getValue())) {
            readTextBook(chapter_index);
        } else if (type.equals(BookType_Enum.MAGAZINE.getValue())) {
            readMagazineBook();
        } else if (type.equals(BookType_Enum.SERIAL.getValue())) {
            readTextBook(chapter_index);
        } else if (type.equals(BookType_Enum.TEXT.getValue())) {
            readTextBook(chapter_index);
        } else if (type.equals(BookType_Enum.UMD.getValue())) {
            Util.showToast(context, "暂时不支持漫画格式书籍阅读");
        } else if (type.equals(BookType_Enum.LISTEN.getValue())) {
            Util.showToast(context, "暂时不支持听书");
        } else {
            Util.showToast(context, "无法识别的书籍类型");
        }
    }

    private int chapter_index = 0;

    /**
     * 是否第一次阅读书籍
     */
    void readBook() {
        //showLoading();
        if (catalogList == null) {
            Util.showToast(context, "此书无目录数据，无法阅读");
            return;
        }
        if (null == bean) {
            //closeLoading();
            Util.showToast(context, "该书已下架");
            return;
        }
        NewActionHelp.qryReadBookByBookId(this, bean.getBookId(), new ObjectHttpResponseHandler<NewBookBean>() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Log.e("1111112", s);
                chapter_index = QyreaderPerferencesUtil.getInstance(context, Const.phone_number).getChapterIndex(String.valueOf(bean.getBookId()));
                addBooktoShelf(BookStatus_Enum.ONLINE.getValue(), chapter_index);
                onlineRead(bean.getContent_type());
            }

            @Override
            public void onSuccess(int i, Header[] headers, NewBookBean bookBean, String s) {
                Log.e("111111", bookBean.getChapterIndex() + "ss");
                chapter_index = bookBean.getChapterIndex();
                NewActionHelp.qryChapterInfo(context, String.valueOf(bean.getBookId()), catalogList.get(chapter_index).getId(), new ObjectHttpResponseHandler<ChapterInfo>() {

                    @Override
                    public Type getType() {
                        return new TypeToken<ChapterInfo>() {
                        }.getType();
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] arg1, String responseString, Throwable arg3) {
                        Log.e("1111112", "1111111111");
                        if (statusCode == 6201 || statusCode == 6202) {
                            try {
                                Utils.showToast(context, JSONUtil.getString(responseString));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] arg1, ChapterInfo arg2, String responseString) {
                        Log.e("111111111", responseString);
                        addBooktoShelf(BookStatus_Enum.ONLINE.getValue(), chapter_index);
                        onlineRead(bean.getContent_type());
                    }
                });
            }

            @Override
            public Type getType() {
                return new TypeToken<NewBookBean>() {
                }.getType();
            }
        });
//        chapter_index = QyreaderPerferencesUtil.getInstance(context, Const.phone_number).getChapterIndex(String.valueOf(bean.getBookId()));
//        NewActionHelp.qryChapterInfo(context, String.valueOf(bean.getBookId()), catalogList.get(chapter_index).getId(), new ObjectHttpResponseHandler<ChapterInfo>() {
//
//            @Override
//            public Type getType() {
//                return new TypeToken<ChapterInfo>() {
//                }.getType();
//            }
//
//            @Override
//            public void onFailure(int statusCode, Header[] arg1, String responseString, Throwable arg3) {
//                Log.e("1111112",responseString);
//                if (statusCode == 6201 || statusCode == 6202) {
//                    try {
//                        Utils.showToast(context, JSONUtil.getString(responseString));
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//
//            @Override
//            public void onSuccess(int statusCode, Header[] arg1, ChapterInfo arg2, String responseString) {
//                addBooktoShelf(BookStatus_Enum.ONLINE.getValue(), chapter_index);
//                onlineRead(bean.getContent_type());
//            }
//        });
    }


    /**
     * 下载书籍
     */
    void downloadBook() {
        if (downloadMap.size() > MAX_DOWNLOAD_SIZE) {
            Util.showToast(context, "最多同时下载" + MAX_DOWNLOAD_SIZE + "本书籍");
        } else {
            ++notificationId;
            currNotificationId = notificationId;
            downloadMap.put(currNotificationId, bean);
            manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            notif = new Notification();
            notif.icon = R.drawable.bookcover_default;
            notif.flags = Notification.FLAG_ONLY_ALERT_ONCE;
            notif.tickerText = "下载";
            // 通知栏显示所用到的布局文件

            notif.contentView = new RemoteViews(getPackageName(), R.layout.notice_dialog_lay);
            notif.contentView.setTextViewText(R.id.mobile_kan_dian, bean.getName());
            notif.contentView.setImageViewUri(R.id.content_view_image, Uri.parse(bean.getLogoUrl()));
            notif.contentIntent = getPendingIntent(true);

            manager.notify(notificationId, notif);
            BaseSimpleActivity.notificationMap.put(notificationId, DefaultConsts.DOWNLOAD_NOTIFICATION_FLAG);
//			new DownloadForProgressAction(context, downInfo.getUrl(), FileUtil.DownloadPath() + bean.getBookId() + ".ceb", new DownBookProgress(notificationId)).start();

            currDownloadPath = FileUtil.DownloadPath() + bean.getBookId() + suffix;
            new DownloadForProgressAction(context, downInfo.getUrl(), currDownloadPath, new DownBookProgress(notificationId)).start();
        }
    }

    private PendingIntent getPendingIntent(boolean isEmpty) {
        //通知栏点击事件
        if (isEmpty) {
            pIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
        } else {
            Intent intent = new Intent();
//			intent.setClass(context, ReadingBookActivity.class);
//			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
//			String urlpath = "";
//			int index = QyreaderPerferencesUtil.getInstance(this, Const.phone_number).getLocalIndex(String.valueOf(bean.getBookId()));
//			urlpath = FileUtil.DownloadPath() + bean.getBookId();
//			urlpath = urlpath + "/" + "oebps";
//			Uri bookurl = Uri.parse(urlpath);
//			intent.setData(bookurl);
//			intent.putExtra(ReadingBookActivity.BOOKSTATUS, 3);
//			intent.putExtra(DefaultConsts.book_contentId_s, String.valueOf(bean.getBookId()));
//			intent.putExtra(DefaultConsts.book_name, bean.getName());
//			intent.putExtra(DefaultConsts.chapterId_index_i, index);
//			intent.setAction(ReadingBookActivity.SHOW_CATALOG);

            if (bean.getDownType().equals("103")) {
                intent.setClass(context, ReadingEpubActivity.class);
                intent.putExtra("BookID", bean.getBookId());
                intent.setData(Uri.parse(currDownloadPath));
            } else {
                intent.setClass(context, ReadingBookActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                int index = QyreaderPerferencesUtil.getInstance(this, Const.phone_number).getLocalIndex(String.valueOf(bean.getBookId()));
                String urlpath = FileUtil.DownloadPath() + bean.getBookId() + "/" + "oebps";
                Uri bookurl = Uri.parse(urlpath);
                intent.setData(bookurl);
                intent.putExtra(ReadingBookActivity.BOOKSTATUS, 3);
                intent.putExtra(DefaultConsts.book_contentId_s, String.valueOf(bean.getBookId()));
                intent.putExtra(DefaultConsts.book_name, bean.getName());
                intent.putExtra(DefaultConsts.chapterId_index_i, index);
                intent.setAction(ReadingBookActivity.SHOW_CATALOG);
            }
            pIntent = PendingIntent.getActivity(context, 0, intent, 0);
        }
        return pIntent;
    }

//	private Bitmap getBitmap(String url) {
//		webImage = new WebImage(url);
//		return webImage.getBitmap(this);
//	}

    TaskProgressType taskType;
    long progressIncress = 0;
    long progressMax = 0;

    /**
     * 下载进度条
     */
    class DownBookProgress implements IoTaskProgress {
        private int id;

        public DownBookProgress(int id) {
            super();
            this.id = id;
        }

        @Override
        public void createProgress(HttpType httpType, TaskProgressType type, long max) {

        }

        @Override
        public void updateProgress(HttpType httpType, TaskProgressType type, long increase, long max) {
            progressIncress = increase;
            progressMax = max;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    notif.contentView.setTextViewText(R.id.content_view_text1, Util.getPercent(progressIncress, progressMax, 0) + "%");
                    tvDownload.setText("下载" + " " + Util.getPercent(progressIncress, progressMax, 0) + "%");
                    //					tvDownload.setEnabled(false);
                    notif.contentView.setProgressBar(R.id.ProgressBar_myStyle, 100, Integer.valueOf(Util.getPercent(progressIncress, progressMax, 0)), false);
                    manager.notify(id, notif);
                }
            });

        }

        @Override
        public void finishProgress(HttpType httpType, TaskProgressType type) {
            taskType = type;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (taskType.name().equals("complete")) {
                        LogUtil.d("hss", "下载书籍完成了");
                        if (id == currNotificationId) {
                            tvDownload.setText("已下载");
                            //							tvDownload.setEnabled(false);
                            isDown = true;
                        }

                        notif.contentView.setProgressBar(R.id.ProgressBar_myStyle, 100, 100, false);
                        notif.contentView.setTextViewText(R.id.content_view_text1, "下载完成");
                        notif.contentIntent = getPendingIntent(false);
                        notif.flags |= Notification.FLAG_AUTO_CANCEL;

                        //解压ceb 文件
                        if ("101".equals(bean.getDownType())) {
                            bookMarkDao.addBooktoShelf(toBookBean(BookStatus_Enum.DOWNLOAD.getValue(), 0, bean));
                        }
                        if (null != bean && !TextUtils.isEmpty(bean.getDownType()) && "103".equals(bean.getDownType())) {
                            initCSS(bean.getBookId());
                            String filePath = FileUtil.DownloadPath() + bean.getBookId() + EpubConst.EPUB_SUFFIX;
                            BookBean bookbean = new BookBean(BookStatus_Enum.DOWNLOAD.getValue(), bean.getBookId(), bean.getName(), BookBean.BOOK_TYPE_EPUB3, 0, filePath, bean.getAuthor(), Const.phone_number, String.valueOf(System.currentTimeMillis()), bean.getLogoUrl());
                            addEpubtoShelf(bookbean);
                        }
                        manager.notify(id, notif);
                    } else if (taskType.name().equals("cancle") || taskType.name().equals("error")) {
                        if (id == currNotificationId) {
                            tvDownload.setText("下载");
                            //							tvDownload.setEnabled(true);
                        }
                        isDown = false;
                        /* 下载失败，删除文件 */
                        FileUtil.delFile(FileUtil.DownloadPath() + bean.getBookId() + suffix);
//						FileUtil.delFile(FileUtil.DownloadPath() + bean.getBookId() + ".ceb");
                        notif.contentView.setTextViewText(R.id.content_view_text1, "下载失败");
                        manager.notify(id, notif);
                    }
                    downloadMap.remove(id);
                }
            });
        }
    }

    /**
     * 下载目录
     *
     * @param url 设定文件
     */
    void downloadDirecoty(String url) {
        new DownloadForProgressAction(this, url, FileUtil.OnlinePath(String.valueOf(bean.getBookId())) + FileUtil.Book_CATALOGUE, new DirecotryProgress()).start();
        isDownloadingCatalog = true;
    }

    class DirecotryProgress implements IoTaskProgress {

        @Override
        public void createProgress(HttpType httpType, TaskProgressType type, long max) {

        }

        @Override
        public void updateProgress(HttpType httpType, TaskProgressType type, long increase, long max) {

        }

        @Override
        public void finishProgress(HttpType httpType, TaskProgressType type) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    //					updateLoadingView(1);
                    //					Util.showToast(context, "目录已下载完成");
                    tvTotalChapter.setText(getResources().getString(R.string.chapter_total, bean.getTotalChapters()));
                    initDirctory(BookStatus_Enum.ONLINE.getValue());
                    isDownloadingCatalog = false;
                }
            });
        }
    }

    /**
     * 获取文件下载内容
     */
    private void getDownloadInfo() {
        //		new DownLoadContentAction(this, bean.getBookId(), bean.getDownType(), new DownListener()).start();
        NewActionHelp.downLoadContent(this, bean.getBookId(), bean.getDownType(), new DownHandler());
    }

    private class DownHandler extends ObjectHttpResponseHandler<DownLoadInfo> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Log.i(responseString);
            if (statusCode == 6201 || statusCode == 6202) {
                try {
                    Utils.showToast(context, JSONUtil.getString(responseString));
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return;
            }
            Util.showToast(context, "目前暂时无法下载，请稍后再试");
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, DownLoadInfo object, String responseString) {
            if (object != null) {
                downInfo = object;
                handler.sendEmptyMessage(GET_CHAPTERLIST_OK);
            } else {
                Util.showToast(context, "书籍下载信息为空，无法下载！");
            }
        }

        @Override
        public Type getType() {
            return new TypeToken<DownLoadInfo>() {
            }.getType();
        }
    }

    class DownListener implements ActionListener {

        @Override
        public void OK(Object obj) {
            if (obj != null) {
                downInfo = (DownLoadInfo) obj;
                handler.sendEmptyMessage(GET_CHAPTERLIST_OK);
            } else {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Util.showToast(context, "书籍下载信息为空，无法下载！");
                    }
                });
            }
        }

        @Override
        public void ERROR(int resultCode, String message) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Util.showToast(context, "目前暂时无法下载，请稍后再试");
                }
            });
        }

        @Override
        public void HTTPERROR(int statusCode) {

        }
    }

    private void initDirctory(int status) {
        String dirctory = "";
        if (status == BookStatus_Enum.ONLINE.getValue()) {
            dirctory = FileUtil.OnlinePath(String.valueOf(bean.getBookId())) + FileUtil.Book_CATALOGUE;
        } else if (status == BookStatus_Enum.LOCAL.getValue()) {
            dirctory = FileUtil.DownloadPath() + bean.getBookId() + "/META-INF/book.ncx";
        }
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser;
        try {
            parser = factory.newSAXParser();
            InputStream is = new FileInputStream(new File(dirctory));
            NCXHandler handle = new NCXHandler();
            parser.parse(is, handle);
            is.close();
            if (null != catalogList && catalogList.size() > 0) catalogList.removeAll(catalogList);
            catalogList = handle.getNavPointList();
        } catch (IOException | SAXException | ParserConfigurationException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param flag 0:加载中，1：加载完成，-1：加载失败
     */
    private void updateLoadingView(int flag) {
        switch (flag) {
            case -1:
                loadingView.setVisibility(View.VISIBLE);
                body.setVisibility(View.GONE);
                if (animationDrawable != null && animationDrawable.isRunning()) {
                    animationDrawable.stop();
                }
                loadingImg.setBackgroundResource(R.drawable.home_loading_fail);
                break;
            case 0:
                loadingView.setVisibility(View.VISIBLE);
                body.setVisibility(View.GONE);
                loadingImg.setBackgroundResource(R.drawable.home_progress);
                animationDrawable = (AnimationDrawable) loadingImg.getBackground();
                animationDrawable.start();
                break;
            case 1:
                loadingView.setVisibility(View.GONE);
                body.setVisibility(View.VISIBLE);
                break;
        }
    }

    private class BookInfoHandler extends ObjectHttpResponseHandler<BookInfo> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            closeLoading();
            if (statusCode > 1000) {
                handler.sendEmptyMessage(GET_BOOKINFO_ERROR);
            }
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, BookInfo object, String responseString) {
            bean = object;
            closeLoading();
            handler.sendEmptyMessage(GET_BOOKINFO_OK);
        }

        @Override
        public Type getType() {
            return new TypeToken<BookInfo>() {
            }.getType();
        }

    }

    class BookInfoListener implements ActionListener {

        @Override
        public void OK(Object obj) {
            bean = (BookInfo) obj;
            closeLoading();
            handler.sendEmptyMessage(GET_BOOKINFO_OK);
        }

        @Override
        public void ERROR(int resultCode, String message) {
            closeLoading();
            handler.sendEmptyMessage(GET_BOOKINFO_ERROR);
        }

        @Override
        public void HTTPERROR(int statusCode) {
            closeLoading();
        }
    }

    /**
     * 获取书籍评论的 action listener
     */
    private class BookCommentsActionListener extends BaseAction {
        @SuppressWarnings("unchecked")
        @Override
        public void OK(Object obj) {
            bookComments = (List<CommentBean>) obj;
            //刷新UI
            handler.post(new Runnable() {
                @Override
                public void run() {
                    //更新子list view
                    commenetsAdapter.notifyDataSetChanged();
                    if (bookComments == null || bookComments.size() == 0) {
                        updateCommentsHintUI(1);//加载的内容为空
                    } else {
                        updateCommentsHintUI(2);//加载成功
                    }
                    updateCommentsNumber(false);
                }
            });
        }

        @Override
        public void onError() {
            super.onError();
            //通知 外部的调用者， 出错了。
            handler.post(new Runnable() {
                @Override
                public void run() {
                    //todo 处理UI的不同显示
                    //Util.showToast(mContext, "获取书籍评论失败");
                    updateCommentsHintUI(-1);//加载失败
                }
            });
        }
    }

    //跟新评论数
    private void updateCommentsNumber(boolean isInit) {
        String countStr = "评论";
        if (commentsCount > 0) {
            countStr = countStr + "（" + commentsCount + "）";
        }
        tv_book_comment.setText(countStr);
        if (!isInit && commentsCount > BOOKCOMMENTS_MAX_SIZE) {
            // 显示加载理多
            tv_getmore.setVisibility(View.VISIBLE);
        } else {
            tv_getmore.setVisibility(View.GONE);
        }
    }

    /**
     * 获取书籍评论数的 action listener
     */
    private class BookCommentsNumberActionListener extends BaseAction {
        private boolean isInit;

        public BookCommentsNumberActionListener(boolean isInit) {
            this.isInit = isInit;
        }

        @SuppressWarnings("unchecked")
        @Override
        public void OK(Object obj) {
            final NumberInfo numbers = (NumberInfo) obj;
            commentsCount = numbers.commentNum;
            //刷新UI
            if (isInit) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //更新UI
                        updateCommentsNumber(isInit);
                    }
                });
            }
        }

        @Override
        public void onError() {
            super.onError();
            //通知 外部的调用者， 出错了。
            handler.post(new Runnable() {
                @Override
                public void run() {
                    //todo 处理UI的不同显示
                    Util.showToast(NewBookDetailActivity.this, "获取书籍评论数失败");
                }
            });
        }
    }

    private class BookCommentsAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            if (bookComments == null) return 0;
            return bookComments.size();
        }

        @Override
        public Object getItem(int position) {
            return bookComments.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            view = LayoutInflater.from(context).inflate(R.layout.comment_comment_content_item, null);
            CommentItemViewHolder ItemViewHolder = new CommentItemViewHolder();
            ItemViewHolder.im_head = (CircleImageView) view.findViewById(R.id.im_head);
            ItemViewHolder.tv_name = (TextView) view.findViewById(R.id.tv_name);
            ItemViewHolder.tv_time = (TextView) view.findViewById(R.id.tv_time);
            ItemViewHolder.tv_content = (TextView) view.findViewById(R.id.tv_content);
            //设置内容
            CommentBean commentItem = bookComments.get(position);
            if (Util.isNotEmpty(commentItem.getCommentUserHeadImage())) {
                ImageLoaderUtil.loadWebUrl(commentItem.getCommentUserHeadImage(), ItemViewHolder.im_head);
            }
            ItemViewHolder.tv_name.setText(commentItem.getCommentUserNickName());
            ItemViewHolder.tv_time.setText(DateUtil.getRegionTime(commentItem.getCreateTime()));
            ItemViewHolder.tv_content.setText(getContent(commentItem));
            return view;
        }

        private String getContent(CommentBean bean) {
            if (null != bean) {
                return Util.isEmpty(bean.replyCommentUserNickName) ? bean.content : String.format("回复%s: %s", bean.replyCommentUserNickName, bean.content);
            }
            return "";
        }

        private String getNickName(CommentBean bean) {
            if (null == bean) return "";
            if (Util.isNotEmpty(bean.commentUserNickName)) return bean.commentUserNickName;
            final String account = bean.commentUserAccount;
            if (Util.isEmpty(account)) return "";
            return Util.formatPhone(account);
        }
    }

    private String suffix;
    private String currDownloadPath;

    private void readEpub3() {
        String filePath = FileUtil.DownloadPath() + bean.getBookId() + EpubConst.EPUB_SUFFIX;
        if (!new File(filePath).exists()) {
            Util.showToast(context, "当前书籍需要先下载才能查看，是否下载书籍");
            return;
        }
        BookBean bookbean = new BookBean(BookStatus_Enum.DOWNLOAD.getValue(), bean.getBookId(), bean.getName(), BookBean.BOOK_TYPE_EPUB3, 0, filePath, bean.getAuthor(), Const.phone_number, String.valueOf(System.currentTimeMillis()), bean.getLogoUrl());
        addEpubtoShelf(bookbean);
        goEpub(filePath);
    }

    private void goEpub(String epubPath) {
        Intent intent = new Intent(context, ReadingEpubActivity.class);
        intent.putExtra("BookID", bean.getBookId());
        intent.setData(Uri.parse(epubPath));
        startActivity(intent);
    }

    /**
     * epub3电子书添加到书架
     */
    private void addEpubtoShelf(BookBean bookbean) {
        bookMarkDao.addBooktoShelf(bookbean);
    }

    private void initCSS(final long bookId) {
        final String savePath = EpubConst.EPUB_CSS_LOCAL_PATH + bookId + "/" + EpubConst.EPUB_CSS_NAME;
        new Thread(new Runnable() {
            @Override
            public void run() {
                CSSHelp.unZipCSS(bookId);
                CSSHelp.parse(context, savePath);
            }
        }).start();
    }
}
